<?php

/**

 * Created by PhpStorm.

 * User: win7

 * Date: 2018/7/18 0018

 * Time: 15:43

 */



namespace Home\Controller;





use Think\Controller;



class CreateXmlController extends Controller
{

    public function urlset(){
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限

//        for($i = 1; $i< 50000;$i++){
        $i = M("conf")->where("id = 3")->getField('value');//当前XML子文件名
        $sql=M('news')->page($i,4888)->field('id')->order('id asc')->select();   //从数据库中读取数据

        if(empty($sql)){
            $this->sitemapindex($i);
        }//end if



        $xml_header = '<?xml version="1.0" encoding="utf-8"?>';



        //创建节点urlset

        $xml_header .= '<urlset>';


        if (file_exists('./xml/'.$i.'.xml'))unlink('./xml/'.$i.'.xml');//删除xml



        $xml_hand = fopen('./xml/'.$i.'.xml','w');//打开xml

        fwrite($xml_hand,$xml_header);//写入xml



        foreach ($sql as $k=>$v){

            //创建节点url

            $xml = '<url>';



            //创建节点loc

            $xml .= '<loc>';

            $xml .= 'http://zixun.xiangtws.com/Home/News/info/nid/'.$v['id'];

            $xml .= '</loc>';



            //创建节点lastmod

            $xml .= '<lastmod>';

            $xml .= date('Y-m-d',time());

            $xml .= '</lastmod>';



            //创建节点changefreq

            $xml .= '<changefreq>';

            $xml .= 'daily';

            $xml .= '</changefreq>';



            //创建节点priority

            $xml .= '<priority>';

            $xml .= round($v['view']/100,1)>1 ? 1:round($v['view']/100,1);

            $xml .= '</priority>';





            $xml .= '</url>';

            fwrite($xml_hand,$xml);//写入内容

        }//end foreach



        $xml_footer = '</urlset>';

        fwrite($xml_hand,$xml_footer);//写入结尾
        M("conf")->where("id = 3")->setInc('value',1);//生成XML子文件名
//        }//end for
    }//end fun



    public function sitemapindex($num){

        $xml_header = '<?xml version="1.0" encoding="utf-8"?>';

        $xml_header .= "<sitemapindex>";



        if (file_exists('./xml/all.xml'))unlink('./xml/all.xml');//删除xml



        $xml_hand = fopen('./xml/all.xml','w');//打开xml

        fwrite($xml_hand,$xml_header);//写入头部



        for($i = 1; $i< $num;$i++){

            //创建sitemap节点

            $xml = "<sitemap>";



            //创建loc节点

            $xml .= "<loc>";

            $xml .= "http://zixun.xiangtws.com/xml/".$i.".xml";

            $xml .= "</loc>";



            //创建loc节点

            $xml .= "<lastmod>";

            $xml .= date('Y-m-d',time());

            $xml .= "</lastmod>";

            $xml .= "</sitemap>";

            fwrite($xml_hand,$xml);//写入内容

        }//end for

        $xml_footer = "</sitemapindex>";

        fwrite($xml_hand,$xml_footer);//写入结尾
        M("conf")->where("id = 3")->save(['value'=>1]);//重置

    }//end fun

}//end class